'use client';

import { useState, useEffect } from 'react';
import Image from 'next/image';
import MediaSelector from '@/components/admin/MediaSelector';

interface ContactInfo {
  id: string;
  type: 'wechat_group' | 'wechat_official' | 'qq_group' | 'email' | 'phone' | 'address';
  title: string;
  description?: string;
  content: string; // 对于二维码是图片路径，对于其他是文本内容
  qrCode?: string; // 二维码图片路径
  isVisible: boolean;
  order: number;
}

export default function ContactPage() {
  const [contacts, setContacts] = useState<ContactInfo[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchContacts();
  }, []);

  const fetchContacts = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/admin/contact');
      if (response.ok) {
        const data = await response.json();
        if (data.success) {
          setContacts(data.data);
        }
      }
    } catch (error) {
      console.error('Error fetching contacts:', error);
    } finally {
      setLoading(false);
    }
  };

  const [showAddForm, setShowAddForm] = useState(false);
  const [editingContact, setEditingContact] = useState<ContactInfo | null>(null);
  const [showMediaSelector, setShowMediaSelector] = useState(false);
  const [formData, setFormData] = useState({
    type: 'wechat_group' as ContactInfo['type'],
    title: '',
    description: '',
    content: '',
    qrCode: '',
    isVisible: true,
    order: 1
  });

  const typeLabels = {
    wechat_group: '💬 微信群',
    wechat_official: '📢 微信公众号',
    qq_group: '👥 QQ群',
    email: '📧 邮箱',
    phone: '📱 电话',
    address: '📍 地址'
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      if (editingContact) {
        // 更新联系方式
        const response = await fetch('/api/admin/contact', {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ id: editingContact.id, ...formData })
        });
        
        const result = await response.json();
        
        if (response.ok && result.success) {
          alert('更新成功！');
          await fetchContacts();
          setEditingContact(null);
          setShowAddForm(false);
          resetForm();
        } else {
          alert(`更新失败: ${result.error || '未知错误'}`);
        }
      } else {
        // 创建联系方式
        const response = await fetch('/api/admin/contact', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(formData)
        });
        
        const result = await response.json();
        
        if (response.ok && result.success) {
          alert('创建成功！');
          await fetchContacts();
          setShowAddForm(false);
          resetForm();
        } else {
          alert(`创建失败: ${result.error || '未知错误'}`);
        }
      }
    } catch (error) {
      console.error('Error saving contact:', error);
      alert('保存失败，请重试');
    }
  };

  const resetForm = () => {
    setFormData({
      type: 'wechat_group',
      title: '',
      description: '',
      content: '',
      qrCode: '',
      isVisible: true,
      order: 1
    });
  };

  const handleEdit = (contact: ContactInfo) => {
    setEditingContact(contact);
    setFormData({
      type: contact.type,
      title: contact.title,
      description: contact.description || '',
      content: contact.content,
      qrCode: contact.qrCode || '',
      isVisible: contact.isVisible,
      order: contact.order
    });
    setShowAddForm(true);
  };

  const handleDelete = async (id: string) => {
    if (confirm('确定要删除这个联系方式吗？')) {
      try {
        const response = await fetch(`/api/admin/contact?id=${id}`, {
          method: 'DELETE'
        });
        
        if (response.ok) {
          await fetchContacts();
        } else {
          alert('删除失败，请重试');
        }
      } catch (error) {
        console.error('Error deleting contact:', error);
        alert('删除失败，请重试');
      }
    }
  };

  const handleToggleVisibility = async (id: string) => {
    try {
      const contact = contacts.find(c => c.id === id);
      if (!contact) return;

      const response = await fetch('/api/admin/contact', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...contact,
          isVisible: !contact.isVisible
        })
      });
      
      if (response.ok) {
        await fetchContacts();
      } else {
        alert('更新失败，请重试');
      }
    } catch (error) {
      console.error('Error updating contact visibility:', error);
      alert('更新失败，请重试');
    }
  };

  const handleMediaSelect = (files: string[]) => {
    if (files.length > 0) {
      setFormData({ ...formData, qrCode: files[0] });
    }
    setShowMediaSelector(false);
  };

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>, field: 'qrCode') => {
    const file = e.target.files?.[0];
    if (!file) return;

    const uploadFormData = new FormData();
    uploadFormData.append('files', file);

    try {
      const response = await fetch('/api/upload', {
        method: 'POST',
        body: uploadFormData
      });
      
      if (response.ok) {
        const data = await response.json();
        if (data.success && data.data.files.length > 0) {
          setFormData({ ...formData, [field]: data.data.files[0] });
        }
      } else {
        alert('文件上传失败，请重试');
      }
    } catch (error) {
      console.error('Error uploading file:', error);
      alert('文件上传失败，请重试');
    }
  };

  const needsQRCode = (type: ContactInfo['type']) => {
    return ['wechat_group', 'wechat_official', 'qq_group'].includes(type);
  };

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">联系方式管理</h1>
          <p className="text-gray-600 mt-1">管理微信群二维码、公众号和其他联系方式</p>
        </div>
        <button
          onClick={() => setShowAddForm(true)}
          className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
        >
          ➕ 添加联系方式
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white p-4 rounded-lg border">
          <div className="text-2xl font-bold text-green-600">
            {contacts.filter(c => c.type === 'wechat_group').length}
          </div>
          <div className="text-sm text-gray-600">微信群</div>
        </div>
        <div className="bg-white p-4 rounded-lg border">
          <div className="text-2xl font-bold text-blue-600">
            {contacts.filter(c => c.type === 'wechat_official').length}
          </div>
          <div className="text-sm text-gray-600">公众号</div>
        </div>
        <div className="bg-white p-4 rounded-lg border">
          <div className="text-2xl font-bold text-purple-600">
            {contacts.filter(c => ['email', 'phone'].includes(c.type)).length}
          </div>
          <div className="text-sm text-gray-600">直接联系</div>
        </div>
        <div className="bg-white p-4 rounded-lg border">
          <div className="text-2xl font-bold text-yellow-600">
            {contacts.filter(c => c.isVisible).length}
          </div>
          <div className="text-sm text-gray-600">显示中</div>
        </div>
      </div>

      {/* Contact List */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {contacts.map((contact) => (
          <div key={contact.id} className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
            <div className="p-4">
              <div className="flex items-center justify-between mb-2">
                <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                  {typeLabels[contact.type]}
                </span>
                <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                  contact.isVisible ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'
                }`}>
                  {contact.isVisible ? '显示' : '隐藏'}
                </span>
              </div>
              
              <h3 className="text-lg font-semibold text-gray-900 mb-1">
                {contact.title}
              </h3>
              
              {contact.description && (
                <p className="text-sm text-gray-600 mb-3">
                  {contact.description}
                </p>
              )}

              {/* 显示二维码或内容 */}
              {contact.qrCode ? (
                <div className="mb-3">
                  <img 
                    src={contact.qrCode} 
                    alt={contact.title}
                    className="w-32 h-32 object-cover rounded-lg mx-auto bg-gray-100"
                    onError={(e) => {
                      e.currentTarget.src = '';
                    }}
                  />
                </div>
              ) : (
                <div className="mb-3 p-3 bg-gray-50 rounded-lg">
                  <p className="text-sm font-medium text-gray-900">
                    {contact.content}
                  </p>
                </div>
              )}

              <div className="flex items-center justify-between pt-3 border-t border-gray-200">
                <span className="text-xs text-gray-500">
                  排序: {contact.order}
                </span>
                <div className="flex space-x-2">
                  <button
                    onClick={() => handleToggleVisibility(contact.id)}
                    className={`text-sm px-2 py-1 rounded ${
                      contact.isVisible 
                        ? 'bg-green-100 text-green-800 hover:bg-green-200' 
                        : 'bg-gray-100 text-gray-800 hover:bg-gray-200'
                    }`}
                  >
                    {contact.isVisible ? '👁️' : '🙈'}
                  </button>
                  <button
                    onClick={() => handleEdit(contact)}
                    className="text-blue-600 hover:text-blue-800 p-1"
                  >
                    ✏️
                  </button>
                  <button
                    onClick={() => handleDelete(contact.id)}
                    className="text-red-600 hover:text-red-800 p-1"
                  >
                    🗑️
                  </button>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Add/Edit Form Modal */}
      {showAddForm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-xl font-bold">
                {editingContact ? '编辑联系方式' : '添加联系方式'}
              </h2>
              <button
                onClick={() => {
                  setShowAddForm(false);
                  setEditingContact(null);
                  resetForm();
                }}
                className="text-gray-500 hover:text-gray-700"
              >
                ✕
              </button>
            </div>

            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    类型 *
                  </label>
                  <select
                    required
                    value={formData.type}
                    onChange={(e) => setFormData({ ...formData, type: e.target.value as any })}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="wechat_group">💬 微信群</option>
                    <option value="wechat_official">📢 微信公众号</option>
                    <option value="qq_group">👥 QQ群</option>
                    <option value="email">📧 邮箱</option>
                    <option value="phone">📱 电话</option>
                    <option value="address">📍 地址</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    排序 *
                  </label>
                  <input
                    type="number"
                    required
                    min="1"
                    value={formData.order}
                    onChange={(e) => setFormData({ ...formData, order: parseInt(e.target.value) })}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  标题 *
                </label>
                <input
                  type="text"
                  required
                  value={formData.title}
                  onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                  placeholder="例如：技术交流群"
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  描述
                </label>
                <input
                  type="text"
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  placeholder="例如：讨论机器人技术，分享学习资源"
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  内容 *
                </label>
                <input
                  type="text"
                  required
                  value={formData.content}
                  onChange={(e) => setFormData({ ...formData, content: e.target.value })}
                  placeholder={
                    needsQRCode(formData.type) 
                      ? "例如：扫码加入微信群" 
                      : "例如：contact@roboticslab.com"
                  }
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

              {needsQRCode(formData.type) && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    二维码图片
                  </label>
                  
                  {/* 显示当前图片 */}
                  {formData.qrCode && (
                    <div className="mb-3">
                      <div className="w-32 h-32 bg-gray-100 rounded-lg overflow-hidden">
                        <Image
                          src={formData.qrCode}
                          alt="二维码预览"
                          width={128}
                          height={128}
                          className="object-cover w-full h-full"
                          onError={(e) => {
                            e.currentTarget.src = '';
                          }}
                        />
                      </div>
                      <p className="mt-1 text-xs text-gray-500">{formData.qrCode}</p>
                    </div>
                  )}
                  
                  <div className="flex gap-2">
                    {/* 从媒体库选择 */}
                    <button
                      type="button"
                      onClick={() => setShowMediaSelector(true)}
                      className="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors text-sm"
                    >
                      📁 从媒体库选择
                    </button>
                    
                    {/* 直接上传 */}
                    <label className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors text-sm cursor-pointer">
                      📤 上传新图片
                      <input
                        type="file"
                        onChange={(e) => handleFileUpload(e, 'qrCode')}
                        accept="image/*"
                        className="hidden"
                      />
                    </label>
                    
                    {/* 清除图片 */}
                    {formData.qrCode && (
                      <button
                        type="button"
                        onClick={() => setFormData({ ...formData, qrCode: '' })}
                        className="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700 transition-colors text-sm"
                      >
                        🗑️ 清除
                      </button>
                    )}
                  </div>
                </div>
              )}

              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="isVisible"
                  checked={formData.isVisible}
                  onChange={(e) => setFormData({ ...formData, isVisible: e.target.checked })}
                  className="mr-2"
                />
                <label htmlFor="isVisible" className="text-sm font-medium text-gray-700">
                  在网站上显示
                </label>
              </div>

              <div className="flex justify-end space-x-3 pt-4">
                <button
                  type="button"
                  onClick={() => {
                    setShowAddForm(false);
                    setEditingContact(null);
                    resetForm();
                  }}
                  className="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50"
                >
                  取消
                </button>
                <button
                  type="submit"
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                >
                  {editingContact ? '更新' : '添加'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* 媒体选择器 */}
      <MediaSelector
        isOpen={showMediaSelector}
        onClose={() => setShowMediaSelector(false)}
        onSelect={handleMediaSelect}
        multiple={false}
        title="选择二维码图片"
      />
    </div>
  );
}